<template>
	<view class="content-box root-style">
		<view v-if="IsFinish">
			<view @click="playMp3(item.MP3)" v-for="item in examDetail" :key="item.WordId" class="rstitem">
				<view style="font-size: var(--text-16); font-weight: bold; margin-bottom:15rpx;    align-items: center; display: flex; justify-items: center; ">
					<view style="flex: 1;">{{item.Word}}</view>
					<view style="flex: 1;margin-left: 10rpx;" @click="item.show=true">
						<view v-if="item.IsRight || item.show">{{item.Mean}}</view>
						<u-icon v-else color="#C9CACA" size="40" name="eye-fill"></u-icon>
					</view>
					<view style="width: 90rpx;text-align: center;">
						<u-icon :color="item.IsRight?'#009B4C':'#E62129'" size="40"
							:name="item.IsRight?'checkmark-circle-fill':'close-circle-fill'"></u-icon>
					</view>
				</view> 
			</view>
		</view>
		<view v-else>
			<view class="detail" v-if="examDetail.length>0">
				<!-- <single-selection @next="getNextflag" :effect="true" :pause="true" :current="current" :data="examDetail" :type="type"></single-selection> -->
				<pairing-elimination :word-list="examDetail" @sendProcess="sendProcess" @gameover="gameover"></pairing-elimination>
			</view>
		</view>

		<!-- <u-button @tap="handelNext" class="next-btn w-full" type="warning" :plain="true"><view class="next-text">继续</view></u-button> -->
	</view>
</template>

<script lang="ts" setup>
	import { onLoad } from '@dcloudio/uni-app';
	import { ref, onMounted, nextTick, watch } from 'vue';
	import { OT, ktlapi } from '@/utils';
	import { IWord, TestTemplates, useStudyStore } from '@/store/study';
	import { useTest } from '@/common/hooks';
	import PairingElimination from '@/pages-study/components/pairing-elimination/pairing-elimination.vue';
	import SingleSelection from '@/pages-study/components/single-selection/single-selection.vue';
	const ExamId = ref("")
	const current = ref(null);
	const examInfo = ref(null);
	const examDetail = ref([]);
	const isOver = ref(false);
	const type = ref(null);
	const errorCount = ref(0);
	const CFCount = ref(0);
	const IsOver = ref(false);
	const rightPct = ref(0);
	const useTemplates = ref([]);
	const Mode = ref("");
	const IsFinish = ref(false);
	const renderTest = ref(false);
	/** 步骤：最终结果反馈 */
	defineOptions({ name: 'step-final-result', inheritAttrs: false });

	const emit = defineEmits(['next', 'module-event']);

	const props = defineProps(["id", "mode"])
	const testUtil = useTest();

	var socketTask = null;
	
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	// 声明函数
	function playMp3(mp3: string){ 
		if (mp3.includes('http')) {
			innerAudioContext.src = mp3;
		} else {
			innerAudioContext.src = 'https://nx5.abc5g.com/' + mp3;
		}
		innerAudioContext.play();
		innerAudioContext.onPlay(() => {
			
		});
		innerAudioContext.onError((res) => {
		  console.log(res.errMsg);
		  console.log(res.errCode);
		});
		 
	}
	
	const finishCount = ref(0);
	
	function sendProcess(){
		finishCount.value += 1;
		console.log('每完成一个告诉教师端，显示进度', finishCount.value+'/'+examDetail.value.length);
		socketTask.send({
			data: JSON.stringify({
				Action: "ExamProcess",
				Message: JSON.stringify({
					ExamId: ExamId.value,
					Role: "Student",
					Msg:finishCount.value+'/'+examDetail.value.length
				}),
				Callback: "ExamProcess"
			})
		});
	}

	onLoad(query => {
		console.log("onLoad", "onLoad")
		if (query.ExamId) {
			ExamId.value = query.ExamId;
			Mode.value = query.Mode;
			console.log("query", query);
		} else {
			ExamId.value = props.id;
			Mode.value = props.mode;
			console.log("props", props);
		}
	})

	function gameover() {
		var rightCount = examDetail.value.filter(x => {
			return x.errorCount == 0
		}).length;

		rightPct.value = Math.round(rightCount / examDetail.value.length * 100);
		uni.showLoading({
			title: '加载中'
		});

		var details = [];
		for (var i = 0; i < examDetail.value.length; i++) {
			details.push({ 
				"ID": examDetail.value[i]["ID"],
				"ErrorCount": examDetail.value[i]["errorCount"]
			});
		}
		
		ktlapi({
			apiurl:OT.CommandAddSet,
			action: "UpdateExamDetail",
			data: details
		}).then((res : any) => {
			ktlapi({
				action: "Cus_FinishExam",
				data: {
					ExamId: ExamId.value,
					RightPct: rightPct.value
				}
			}).then((res : any) => {
				IsFinish.value = true;
				uni.hideLoading();
				loadExam();
				socketTask.send({
					data: JSON.stringify({
						Action: "ExamFinish",
						Message: JSON.stringify({
							ExamId: ExamId.value,
							Role: "Student"
						}),
						Callback: "ExamFinish"
					})
				});
			});
		}) 
	}

	watch(() => props.id, (nVal : string) => {
		if (typeof (nVal) == 'undefined') {
			return;
		}
		ExamId.value = nVal
		console.log("nVal", nVal);
	}, { immediate: true, deep: true })

	const studyStore = useStudyStore();

	function loadExam() {
		uni.showLoading({
			title: '加载中'
		});
		ktlapi({
			apiurl: OT.CommandSet,
			action: "Cus_GetExam",
			data: {
				ID: ExamId.value
			}
		}).then((res : any) => {

			uni.hideLoading();
			examInfo.value = res.data.tables[0].table[0];
			IsFinish.value = examInfo.value["IsFinished"];
			examDetail.value = res.data.tables[1].table;
			console.log(examDetail.value);
		});
	}

	onMounted(() => {
		console.log("onMounted", ExamId.value);
		loadExam();

		if (Mode.value != 'resp') {
			socketTask = uni.connectSocket({
				url: 'wss://nx5.abc5g.com/apis/WSS/connect', //仅为示例，并非真实接口地址。
				complete: () => {
					console.log('WSS已连接');
				}
			});

			socketTask.onOpen(result => {
				socketTask.send({
					data: JSON.stringify({
						Action: "ExamConnect",
						Message: JSON.stringify({
							ExamId: ExamId.value,
							Role: "Student"
						}),
						Callback: "StudentConnect"
					})
				});
			})
		}
	})

	const handelNext = () => {
		emit('next');
	}
</script>

<style lang="scss" scoped>
	.rstitem {
		margin-bottom: 20rpx;
		border-bottom: 1px solid #C9CACA;
	}

	.content-box {
		--font-color: #332c2b;
		display: flex;
		flex-flow: column;
		flex: 1;
		padding-bottom: 50rpx;
		margin: 0 30rpx;

		.option-box {
			display: flex;
			height: 100rpx;
			align-items: center;

			.left {
				flex: 1;
				display: flex;
				align-items: center;

				.read-text {
					color: #757475;
					margin-right: 20rpx;
					font-size: var(--text-18);
				}
			}

			.process {
				padding: 10rpx 14rpx;
				color: #f55f22;
				background-color: #fed7c6;
				border-radius: 30rpx;
				min-width: 150rpx;
				text-align: center;
			}
		}

		.detail {
			flex: 1;
			padding-top: 55rpx; 
		}
	}

	.next-text {
		font-size: var(--text-18);
		font-weight: bold;
		display: flex;
	}

	/* 针对 1280px 分辨率 */
	@media(min-width:1200px) {
		.content-box {
			width: 2400rpx;
			margin: 0 auto;
		}

		.process {
			min-width: 238rpx;
		}

		.detail {}
	}
</style>